'''※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
File Name: mysqldb2.py
Author: GID5564
Description: 带配置文件的mysql操作封装
Version: 1.0
Created Time: 04/09/23-09:59:30
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※'''
  
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pymysql
from common.getConfig import myCof
 
 
"""
封装mysql操作
"""
 
 
class OpeartorDB(object):
   
        def connectDB(self):
        """
        连接数据库
        :return: 返回成功失败，原因
        """
        host = myCof.getValue('db', 'host')
        port = myCof.getValue('db', 'port')
        user = myCof.getValue('db', 'user')
        pwd = myCof.getValue('db', 'pwd')
        database = myCof.getValue('db', 'database')
        charset = myCof.getValue('db', 'charset')
        try:
            self.db = pymysql.connect(host=host, port=int(port), user=user, password=pwd, database=database,
                                      charset=charset)
            return True, '连接数据成功'
        except Exception as e:
            return False, '连接数据失败【' + str(e) + '】'
 
    def closeDB(self):
        """
        关闭数据连接.
        :return:
        """
        self.db.close()
 
    def excetSql(self, enpsql):
        """
        执行sql方法，
        """
        go, result = self.connectDB()
        if go is False:
            return go, result
        try:
            cursor = self.db.cursor()
            cursor.execute(enpsql)
            res = cursor.fetchone()  
            if res is not None and 'select' in enpsql.lower():  # 判断是不是查询，
                des = cursor.description[0]
                result = dict(zip(des, res))  # 将返回数据格式化成JSON串
            elif res is None and ('insert' in enpsql.lower() or 'update' in enpsql.lower()):  # 判断是不是插入或者更新数据
                self.db.commit()  # 提交数据操作
                result = ''  # 操作数据，不需要返回数据
            cursor.close()  # 关闭游标
            self.closeDB()  # 关闭数据连接
            return True, result
        except Exception as e:
            return False, 'SQL执行失败,原因：[' + str(e) + ']'
 
 
'''
sql = 'SELECT * FROM stu'
oper = OpeartorDB()
go, result = oper.excetSql(sql)
print(result)
'''